import React from "react";
import moment from "moment";

import Title from "../components/Title";
import Detail from "./components/Detail";
import Sidebar from "./components/Sidebar";
import config from "../config";
import socket from "../Socket";
import commonUtil from "../commonUtil";
import $$8 from '../TitanV81';
import $$E from '../TitanEventManager';

const insulationUpload = (body) =>
	new Promise((resolve, reject) => {
        //console.log(["body", JSON.stringify(body)]);
        $$8.action("S1701M1001A05", {
            body: JSON.stringify(body)
        }, function(res){
            resolve(res);
        }, function(message){
            reject(message);
        });
	});

const Upload = (props) => {
	const [list, setList] = React.useState([]);
	const [load, setLoad] = React.useState(false);
	const [loadText, setLoadText] = React.useState("");
	const [detailFlg, setDetailFlg] = React.useState(false);
	const [item, setItem] = React.useState(0);
	const [percentage, setPercentage] = React.useState(0);
	const [inx, setInx] = React.useState(-1);
	const [dzEnd, setDzEnd] = React.useState(0);
	const [dzStart, setDzStart] = React.useState(0);
	const [dyEnd, setDyEnd] = React.useState(0);
	const [dyStart, setDyStart] = React.useState(0);
	const [allFlg, setAllFlg] = React.useState(false);

    $$E.initEnv(socket, props.match.params.comName);
    $$E.registerOnline("jueyuanReadData", function(data, args) {
        $$8.log("jueyuanReadData.ok", "data", data);
        let row = data.row;
        if($$8.isDefined(row)) {
            if (allFlg) {
                if( ($$8.isEmpty(row.equipment_sn) || row.equipment_sn==="4294967295") 
                    || (row.equipment_sn==="99999999" && row.datime.substring(0,13) === "2000-01-01 01")
                    ) {
                    if (inx < 256) {
                        setInx(256);
                        setPercentage((256 / 512) * 100);
                    } else {
                        setInx(-1);
                        setLoad(false);
                        setPercentage(100);
                    }                
                } else {
                    setList((p) => {
                        p.push(row);
                        return p;
                    });
                    setPercentage(((inx+1) / 512) * 100);
                    if (inx >= 511) {
                        setInx(-1);
                        setLoad(false);
                        setPercentage(100);
                    } else {
                        setInx(inx + 1);
                    }
                }
            } else {
                setList((p) => {
                    p.push(row);
                    return p;
                });
                //$$8.log("inx="+inx, "dzStart="+dzStart, "dzEnd="+dzEnd, "dyStart="+dyStart, "dyEnd="+dyEnd);
                setPercentage(((inx+1) / 512) * 100);
                if (inx < 256) {
                    if (inx === dzEnd) {
                        // 结束后，判断是否有电压数据，如果有继续上传电压数据，没有终止传输
                        if (dyStart !== -1) {
                            setInx(dyStart);
                        } else {
                            setInx(-1);
                            setLoad(false);
                            setPercentage(100);
                        }
                    } else {
                        if(inx===255) {
                            // 处理循环，数据指针到头，重头部开始继续
                            setInx(0);
                        } else {
                            setInx(inx + 1);
                        }
                    }
                } else {
                    if (inx === dyEnd) {
                        setInx(-1);
                        setLoad(false);
                        setPercentage(100);
                    } else {
                        if(inx >= 511) {
                            // 处理循环，数据指针到头，重头部开始继续
                            setInx(256);
                        } else {
                            setInx(inx + 1);
                        }
                    }
                }
            }
        } else {
            $$8.log("jueyuanReadData.error.1");
            setLoad(false);
        }
        return true;
    }, function(data, args){
        $$8.log("jueyuanReadData.error.2");
        setLoad(false);
    });
    $$E.register("clearDevice", function(data, args) {
        //$$8.log("clearDevice.response", "data", data);
        if (data === "err") {
            setLoad(false);
            alert("清除数据失败");
        } else {
			setList([]);
            setInx(-1);
            setLoad(false);
            setPercentage(100);
            $$E.callOnline("jueyuanId4", {read:false});
            alert("数据上传成功,待发数据已清除");
        }
        return true;
    });
    $$E.registerOnline("jueyuanId4", function(data, args) {
        $$8.log("jueyuanId4.ok", "data", data);
        let row = data.row;
        if($$8.isDefined(row)) {
            setDzStart(row.dz_start_index);
            setDzEnd(row.dz_end_index);
            setDyStart(row.dy_start_index);
            setDyEnd(row.dy_end_index);
        } else {
            $$8.log("jueyuanId4.error.1");
            setLoad(false);
        }
        if(args && args.read) {
            setAllFlg(false);
            if (dzEnd !== -1) {
                setLoad(true);
                setList([]);
                setLoadText("正在读取绝缘待发记录(请勿操作页面)...");
                setInx(dzStart);
            } else if (dyEnd !== -1) {
                setLoad(true);
                setList([]);
                setLoadText("正在读取供电待发记录(请勿操作页面)...");
                setInx(dyStart);
            } else {
                setList([]);
                setInx(-1);
                setLoad(false);
                setPercentage(100);
                window.alert("没有可上传数据");
            }
        }
    }, function(data, args){
        $$8.log("jueyuanId4.error.2");
        setLoad(false);
    });

	React.useEffect(() => {
        $$E.callOnline("jueyuanId4", {read:false});
	}, []);

	React.useEffect(() => {
		if (inx !== -1 && load) {
			const num_16 = inx.toString(16);
			let str = "";
			for (let i = 0; i < 4 - num_16.length; i++) {
                str += "0";
            }
            /*
            $$8.log("jueyuanReadData.call"
                , "inx", inx
                , "inx_hex", num_16
                , "str", str
                );
            */
            let hex = config.order["insulation"].get_data.replace(/{NUM}/, str+num_16);
            $$E.call('jueyuanReadData', {'hex':hex});
		}
	}, [inx, props.match.params.comName, load]);

	const toDetail = (item) => {
        /* $$8.log("toDetail", "item", item); */
		setItem(item);
		setDetailFlg(true);
	};

	const readData = () => {
        $$E.callOnline("jueyuanId4", {read:true});
	};

	const readAllData = () => {
        if(confirm("请确认,该操作耗时较长,是否继续?")) {
          setLoad(true);
          setList([]);
          setLoadText("正在读取设备(请勿操作页面)...");
          setAllFlg(true);
          setInx(0);
        }
	};

	const upload = () => {
		setLoad(true);
		setLoadText("正在上传数据请(请勿操作页面)...");
		insulationUpload(list)
			.then((res) => {
				clearDevice();
			})
			.catch((err) => {
				setLoad(false);
				alert("上传失败,请检测网络连接!");
				console.info(err);
			});
	};

	const clearDevice = () => {
		setLoad(true);
		setLoadText("正在清除待发数据(请勿操作页面)...");
        $$E.call('clearDevice');
	};

	return (
		<div className='row'>
			<Sidebar
				category='upload'
				id={props.match.params.id}
				comName={props.match.params.comName}
			/>
			<div className='col-md-10 col-lg-9  offset-md-2'>
				<div className=' card-body mt-3'>
					<Title title='数据上传' load={load} loadText={loadText} />
					<br />
					<div className='row'>
						<div className='col'>
							{detailFlg ? (
								<Detail item={item} back={() => setDetailFlg(false)} />
							) : (
								<table className='table table-sm table-bordered table-hover font-small'>
									<thead className='thead-light'>
										<tr>
											<th colSpan='10'>
												<div className='row'>
													<div className='col'>
														{
															<div
																className='progress p-2'
																style={{ height: "100%" }}
															>
																<div
																	className='progress-bar '
																	role='progressbar'
																	aria-valuenow='60'
																	aria-valuemin='0'
																	aria-valuemax='100'
																	style={{ width: `${percentage}%` }}
																>
																	{parseInt(percentage)}%
																</div>
															</div>
														}
													</div>
													<div
														className='pull-right btn-group btn-group-sm'
														style={{ right: "12px" }}
													>
														<button
															disabled={load}
															className='btn btn-success'
															onClick={readAllData}
														>
															读取全部数据
														</button>
														<button
															disabled={load}
															className='btn btn-info'
															onClick={readData}
														>
															读取待发数据
														</button>
														<button
															disabled={load}
															className='btn btn-primary'
															onClick={upload}
														>
															数据上传
														</button>
													</div>
												</div>
											</th>
										</tr>
										<tr>
											<th>#</th>
											<th>设备编号</th>
											<th>车次</th>
											<th>车次编组</th>
											<th>测试类别</th>
											<th>测试类型</th>
											<th>测试人员</th>
											<th>测试班组</th>
											<th>测试时间</th>
											<th>操作</th>
										</tr>
									</thead>
									<tbody>
										{list &&
											list.map((item, inx) => (
												<tr key={inx}>
													<td>{inx + 1}</td>
													<td>{item.equipment_sn}</td>
													<td>{item.train}</td>
													<td>{item.group}</td>
													<td>{item.datatype}</td>
													<td>{item.category}</td>
													<td>{item.staff}</td>
													<td>{item.team}</td>
													<td>{item.datime}</td>
													<td>
														<button
															className='btn btn-primary btn-sm font-small'
															onClick={() => toDetail(item)}
														>
															查看详情
														</button>
													</td>
												</tr>
											))}
									</tbody>
								</table>
							)}
						</div>
					</div>
				</div>
			</div>
		</div>
	);
};
export default Upload;
